package com.cyf.pay.wxpay.service.impl;

import com.cyf.pay.util.WxNoSensepayConfig;
import com.cyf.pay.wxpay.bean.WxChatUnifiedOrderReq;
import com.cyf.pay.wxpay.bean.WxChatUnifiedOrderRsp;
import com.cyf.pay.wxpay.service.WxNoSensePayService;
import com.cyf.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;

/**
 * @author zym
 * @date 2020/6/23 7:21
 */
@Service
public class WxNoSensePayServiceImpl implements WxNoSensePayService {

    private static final Logger logger = LoggerFactory.getLogger(WxNoSensePayServiceImpl.class);

    @Override
    public WxChatUnifiedOrderRsp unifiedOrder(WxChatUnifiedOrderReq req, String key) {
        try {
            req.setAppid(req.getAppid());
            req.setMch_id(req.getMch_id());
            req.setNotify_url(WxNoSensepayConfig.WECHAT_SCANCODEORDER_URL);
            if (StringUtils.isEmpty(req.getTrade_type())) {
                req.setTrade_type(WxpayConfig.TRADE_TYPE_JSAPI);
            }
            //子商户号              必填字段
            req.setSub_mch_id(req.getSub_mch_id());
            //子商户 公众账号ID
            req.setSub_appid(req.getSub_appid());
            Date date = new Date();
            req.setTime_start(DateUtil.convertDate2Str(date, "yyyyMMddHHmmss"));
            req.setTime_expire(DateUtil.convertDate2Str(DateUtil.getDateAfterSeconds(date, 30 * 60), "yyyyMMddHHmmss"));
            req.setNonce_str(WxpayCore.nonce_str(32));
            req.setTotal_fee(req.getTotal_fee());
            req.setBody(WxNoSensepayConfig.BODY_TYPE_PARKING);
            req.setSpbill_create_ip(WxNoSensepayConfig.SPBILL_CREATE_IP);
            //req.setSign_type("MD5");
            req.setSign(WxpayCore.sign(SignUtil.bean2TreeMap(req), key));
            String tempXmlStr = XmlUtil.beanToXml(new ByteArrayOutputStream(), req);
            String requestXml = tempXmlStr != null ? tempXmlStr.substring(55) : "";
            logger.info("微信公众号，月卡充值请求参数:" + requestXml);
            InputStreamEntity inputStreamEntity = new InputStreamEntity(
                    new ByteArrayInputStream(requestXml.getBytes("UTF-8")), ContentType.APPLICATION_XML);
            String resultXml = HttpsUtil.post(WxpayConfig.UNIFIEDORDER_URL, inputStreamEntity);
            logger.info("微信公众号，月卡充值返回内容:" + resultXml);
            return resultXml != null
                    ? XmlUtil.xmlToBean(resultXml, WxChatUnifiedOrderRsp.class)
                    : new WxChatUnifiedOrderRsp(WxChatUnifiedOrderRsp.FAIL);
        } catch (Exception e) {
            logger.error("{}", e);
            return new WxChatUnifiedOrderRsp(WxChatUnifiedOrderRsp.FAIL);
        }
    }
}
